package com.dmc.controller;


import com.dmc.dict.OrderStatusDict;
import com.dmc.entity.*;
import com.dmc.model.RestListRespResult;
import com.dmc.model.RestResp;
import com.dmc.model.RestRespResult;
import com.dmc.model.User;
import com.dmc.service.GoodsService;
import com.dmc.service.OrderDetailService;
import com.dmc.service.OrdersService;
import com.dmc.service.ShoppingCartService;
import com.dmc.util.ExportUtil;
import com.dmc.util.SessionUtil;
import com.dmc.vo.*;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/order")
@Api(value = "订单相關接口",tags={"OrderController"})
@Slf4j
public class OrderController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private GoodsService goodsService;

    @RequestMapping(value = "/getUserOrder", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户订单详情,可以根据订单状态筛选")
    @ResponseBody
    public RestRespResult<OrdersVo> getUserOrder(Long ordersState,String keyWord) {
        Long currUid = SessionUtil.getCurrUid();
        RestRespResult result = RestRespResult.ok("获取用户订单成功");
        List<OrdersVo> ordersVoList=ordersService.getOrderByUserId(currUid,ordersState,keyWord);
        result.setData(ordersVoList);
        return result;
    }


    @RequestMapping(value = "/getOrder",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="获取所有订单信息")
    public RestRespResult<DataTable<OrdersVo>> getOrder(OrdersVo ordersVo) {
        RestRespResult result = RestRespResult.ok("获取所有订单成功");
        DataTable<OrdersVo> ordersVoDataTable=ordersService.getOrder(ordersVo);
        result.setData(ordersVoDataTable);
        return result;
    }
    @RequestMapping(value = "/getOrderDetailByOrderNo",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="获取所有订单明细")
    public RestRespResult<OrderDetail> getOrderDetailByOrderNo(String ordersNo) {
        RestRespResult result = RestRespResult.ok("获取所有订单明细成功");
        List<OrderDetail> orderDetailList=ordersService.getOrderDetailByOrderNo(ordersNo);
        result.setData(orderDetailList);
        return result;
    }

    /**
     *  待付款订单取消时间：
     *
     * 保存30分钟内未付款，自动取消订单
     *
     *  订单自动确认时间：7天，自动确认到货
     * @param ordersVo
     * @return
     */
    @RequestMapping(value = "/createOrder", method = RequestMethod.POST)
    @ApiOperation(value = "创建订单",tags = {"三期"})
    @ResponseBody
    public RestRespResult<List<String>> createOrder(@RequestBody OrdersVo ordersVo) {
        Assert.notNull(ordersVo, "参数不能为空");
        Assert.isTrue(ordersVo.getUserId()!=null, "用户ID不能为空");
        log.info("createOrder ordersVo:{}",ToStringBuilder.reflectionToString(ordersVo));
        List<String> result=ordersService.createOrder(ordersVo);
        RestRespResult restRespResult=RestRespResult.ok("创建成功");
        restRespResult.setData(result);
        return restRespResult;
    }

    @RequestMapping(value = "/reviewOfflineOrder", method = RequestMethod.POST)
    @ApiOperation(value = "线下支付审核 参数传输orderId即可")
    @ResponseBody
    public RestRespResult<String> reviewOfflineOrder(@RequestBody OrdersVo ordersVo) {
        RestRespResult result = RestRespResult.ok("审核支付成功");
        ordersService.reviewOfflineOrder(ordersVo);
        return result;
    }


    @RequestMapping(value = "/addCart", method = RequestMethod.POST)
    @ApiOperation(value = "加入购物车")
    @ResponseBody
    public RestRespResult<Boolean> addCart(@RequestBody ShoppingCart shoppingCart) {
        RestRespResult result = RestRespResult.ok("加入购物车");
        result.setData(shoppingCartService.addCart(shoppingCart));
        return result;
    }

    @RequestMapping(value = "/getCart", method = RequestMethod.GET)
    @ApiOperation(value = "获取我的购物车,购物车信息和商品信息")
    @ResponseBody
    public RestListRespResult<TGoodsDetailVo> getCart(Long userId) {
        if(userId==null){
            userId=SessionUtil.getCurrUid();
        }
        List<TGoodsDetailVo> shoppingCartList=shoppingCartService.getShoppingCartByUserId(userId);
        RestListRespResult restListRespResult=new RestListRespResult();
        restListRespResult.setData(shoppingCartList);
        return restListRespResult;
    }
    @RequestMapping(value = "/delCart",method = RequestMethod.GET)
    @ApiOperation(value="删除购物车")
    @ResponseBody
    public RestResp delCart(Integer cartId) {
        boolean result=shoppingCartService.deleteById(cartId);
        if(result) {
            return RestResp.ok("删除成功！");
        }else{
            return RestResp.error(RestResp.ERROR,"删除失败！");
        }
    }
    @RequestMapping(value = "/addSkuNum", method = RequestMethod.GET)
    @ApiOperation(value = "检查商品库存数量")
    @ResponseBody
    public RestRespResult<String> addSkuNum(@RequestBody TGoodsSkuVo goodsSkuVo) {
        Assert.notNull(goodsSkuVo, "参数不能为空");
        Assert.isTrue(goodsSkuVo.getId()!=null, "商品不能为空");
        Assert.isTrue(goodsSkuVo.getSkuNum()!=null, "购买数量不能为空");
       String result =goodsService.checkAddSkuNum(goodsSkuVo.getId(),goodsSkuVo.getSkuNum());
        if(StringUtils.isNotBlank(result)) {
            return  RestRespResult.error(RestRespResult.ERROR,result);
        }
        return RestRespResult.ok("可购买，商品库存足够");
    }

    @RequestMapping(value = "/addCartSkuNum", method = RequestMethod.POST)
    @ApiOperation(value = "购物车中增加商品数量")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "userId", value = "用户id",required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "quantity", value = "商品数量",required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "cartId", value = "购物车ID",required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "skuId", value = "商品ID",required = true, dataType = "Long", paramType = "query")
    })
    @ResponseBody
    public RestRespResult<String> addCartSkuNum(@RequestBody ShoppingCart shoppingCart) {
        Assert.notNull(shoppingCart, "参数不能为空");
        Assert.isTrue(shoppingCart.getCartId()!=null, "购物车ID不能为空");
        Assert.isTrue(shoppingCart.getQuantity()!=null, "购买数量不能为空");
        Assert.isTrue(shoppingCart.getSkuId()!=null, "商品ID不能为空");
        Assert.isTrue(shoppingCart.getUserId()!=null, "用户ID不能为空");
        BigDecimal quantity=BigDecimal.valueOf(shoppingCart.getQuantity());
        String result =goodsService.checkAddSkuNum(shoppingCart.getSkuId(),quantity);
        if(StringUtils.isNotBlank(result)) {
            return  RestRespResult.error(RestRespResult.ERROR,result);
        }
        Boolean existShoppingCart=shoppingCartService.addCartSkuNum(shoppingCart);
        if (!existShoppingCart){
            return  RestRespResult.error(RestRespResult.ERROR,"购物车修改商品数量失败");
        }
        return RestRespResult.ok("可购买，商品库存足够");
    }

    @RequestMapping(value = "/getSysOrderConf",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="获取系统设置订单交易配置信息",tags={"三期"})
    public RestRespResult<SysConfVo> getSysOrderConf() {
        RestRespResult restRespResult=RestRespResult.ok("获取信息成功");
        SysConfVo sysConf=ordersService.getSysOrderConf();
        restRespResult.setData(sysConf);
        return restRespResult;
    }

    /**
     * 获取小程序支付方式
     * @return
     */
    @RequestMapping(value="/getSmallPayMode",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取小程序支付方式",tags={"二期"})
    public RestRespResult<List<SmallPayModeVo>> getSmallPayMode() {
        List<SmallPayModeVo> list = ordersService.getSmallPayMode();
        RestRespResult result = RestRespResult.ok("获取小程序支付方式成功");
        result.setData(list);
        return result;
    }

    @RequestMapping(value = "/createOrUpdateSysOrderConf",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="添加或者更新系统设置配置信息",tags={"三期"})
    public RestRespResult<Integer> createOrUpdateSysOrderConf(@RequestBody SysConfVo sysConf) {
        RestRespResult restRespResult=RestRespResult.ok("添加或者更新系统设置配置信息成功");
        Integer reuslt=ordersService.createOrUpdateSysOrderConf(sysConf);
        restRespResult.setData(reuslt);
        return restRespResult;
    }

    @RequestMapping(value = "/getLogisticsInfo",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="获取物流快递公司")
    public RestRespResult<Logistics> getLogisticsInfo() {
        RestRespResult restRespResult=RestRespResult.ok("获取物流快递公司成功");
        List<Logistics> logisticsList=ordersService.getLogisticsInfo();
        restRespResult.setData(logisticsList);
        return restRespResult;
    }

    @RequestMapping(value = "/getOrdersLogisticsList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="获取订单物流信息")
    public RestRespResult<OrdersLogistics> getOrdersLogisticsList(OrdersLogistics ordersLogistics) {
        RestRespResult restRespResult=RestRespResult.ok("获取订单物流信息成功");
        List<OrdersLogistics> ordersLogisticsList=ordersService.getOrdersLogisticsList(ordersLogistics);
        restRespResult.setData(ordersLogisticsList);
        return restRespResult;
    }
    @RequestMapping(value = "/createOrUpdateOrdersLogistics",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="添加或者更新订单快递信息",notes = "发货单功能和退换货功能")
    public RestRespResult<Integer> createOrUpdateOrdersLogistics(@RequestBody OrdersLogistics ordersLogistics) {
        RestRespResult restRespResult=RestRespResult.ok("添加或者更新订单快递信息成功");
        Integer reuslt=ordersService.createOrUpdateOrdersLogistics(ordersLogistics);
        restRespResult.setData(reuslt);
        return restRespResult;
    }

    @RequestMapping(value = "/orderRefund",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="订单退款申请")
    public RestRespResult<Integer> orderRefund(OrdersVo ordersVo) {
        log.error("orderRefund 111,param:{}", ToStringBuilder.reflectionToString(ordersVo));
        RestRespResult result = RestRespResult.ok("订单退款成功");
        Integer resultNum=ordersService.orderRefund(ordersVo);
        result.setData(resultNum);
        return result;
    }

    @RequestMapping(value = "/reviewOrderRefunds",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="订单退款审核")
    public RestRespResult<Integer> reviewOrderRefunds(OrdersVo ordersVo) {
        RestRespResult result = RestRespResult.ok("订单退款审核成功");
        Integer resultNum=ordersService.reviewOrderRefunds(ordersVo);
        result.setData(resultNum);
        return result;
    }

    @RequestMapping(value = "/returnReview",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="订单退货申请")
    public RestRespResult<Integer> returnReview(OrdersLogistics ordersLogistics) {
        RestRespResult result = RestRespResult.ok("订单退货申请成功");
        Integer resultNum=ordersService.returnReview(ordersLogistics);
        result.setData(resultNum);
        return result;
    }

    @RequestMapping(value = "/revokeApply",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="撤销订单申请,1撤销退款申请,2撤销退货申请")
    public RestRespResult<Integer> revokeApply(String ordersNo,Integer type) {
        RestRespResult result = RestRespResult.ok("订单退款成功");
        Integer resultNum=ordersService.revokeApply(ordersNo,type);
        result.setData(resultNum);
        return result;
    }
    @RequestMapping(value = "/reviewOrderReturn",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="订单退货审核")
    public RestRespResult<Integer> reviewOrderReturn(OrdersLogistics ordersLogistics) {
        RestRespResult result = RestRespResult.ok("订单退货审核成功");
        Integer resultNum=ordersService.reviewOrderReturn(ordersLogistics);
        result.setData(resultNum);
        return result;
    }
    @RequestMapping(value = "/cancelOrder",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="取消订单")
    public RestRespResult<Integer> cancelOrder(String ordersNo) {
        RestRespResult result = RestRespResult.ok("取消订单成功");
        Integer resultNum=ordersService.cancelOrder(ordersNo);
        result.setData(resultNum);
        return result;
    }

    @RequestMapping(value = "/useIntegralPay",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="使用积分支付")
    public RestRespResult<Boolean> useIntegralPay(String ordersNo,Long userId,BigDecimal useIntegral) {
        RestRespResult result = RestRespResult.ok("使用积分支付成功");
        ordersService.useIntegralPay(ordersNo,userId,useIntegral);
        result.setData(true);
        return result;
    }

    @RequestMapping(value = "/usebenefitPay",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="使用收益支付",tags = {"三期"})
    public RestRespResult<Boolean> usebenefitPay(@ApiParam(value="订单编号",name="ordersNo")String ordersNo) {
        RestRespResult result = RestRespResult.ok("使用收益支付成功");
        ordersService.useBalancePay(ordersNo);
        result.setData(true);
        return result;
    }


    @RequestMapping(value = "/export",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="导出商品订单")
    public void export(HttpServletResponse response, @RequestBody OrdersVo vo) {
        DataTable<OrdersVo> data=ordersService.getOrder(vo);
        List<OrdersVo> ordersVoList=data.getData();
        List<Object> exportList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(ordersVoList)){
            for (OrdersVo datum : ordersVoList) {
                OrderInfoVo export = new OrderInfoVo();
                export.setOrdersNo(datum.getOrdersNo());
                export.setFinalAmount(datum.getFinalAmount());
                export.setTotalAmount(datum.getTotalAmount());
                export.setOrdersName(OrderStatusDict.getDescByCn(datum.getOrdersState()));
                export.setCreateTime(datum.getCreateTime());
                export.setPayWay(datum.getPayWay());
                export.setReceiverMobile(datum.getReceiverMobile());
                export.setReceiverName(datum.getReceiverName());
                exportList.add(export);
            }
        }
        try {
            ExportUtil.exportModelStart(response,"商品订单",exportList,OrderInfoVo.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping(value = "/userConfirmOrderArrival",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="用户确认收货")
    public RestRespResult<Integer> userConfirmOrderArrival(String ordersNo) {
        RestRespResult result = RestRespResult.ok("用户确认收货成功");
        Integer resultNum=ordersService.userConfirmOrderArrival(SessionUtil.getCurrUid(),ordersNo);
        result.setData(resultNum);
        return result;
    }
}
